var fs = require('fs');
var needle = require('needle');
var logger = require('./Logger');
var GridStore = require('../entity').GridStore;
var DB = require('../entity').DB;
var gm = require('gm').subClass({ imageMagick : true });
var config = require('../config').config;

/**
 *  处理保存头像
 * @param imgUrl
 * @param options {size:64, quality: 80, name: '*.jpg'}
 * @param callback
 */
exports.handleAndSave = function(imgUrl, options, callback){
    needle.get(imgUrl, function(err, resp, body) {
        if(err){
            logger.error('get headimg fail...')
            logger.error(err);
            fs.readFile(config.default_headlogo, {flag:'r'}, function(err, buffer){
                if(err) return callback(err);
                var gridStore = new GridStore(DB, options.name, 'w', {
                    content_type: 'image/jpg'
                });
                gridStore.open(function(err, gridStore){
                    gridStore.write(buffer, function(err, gridStore){
                        gridStore.close(function (err, imgdata) {
                            if(err) logger.error(err.message);
                            logger.debug('user ['+options.name+'] get headlogo failed, use default img...');
                            callback(err, imgdata);
                        })
                    })
                })
            })
        }else{
            gm(body)
                .resize(options.size)
                .quality(options.quality)
                .toBuffer(function (err, buffer) {
                    if(err) return callback(err);
                    var gridStore = new GridStore(DB, options.name, 'w', {
                        content_type: 'image/jpg'
                    });
                    gridStore.open(function(err, gridStore){
                        if(err) return callback(err);
                        gridStore.write(buffer, function(err, gridStore){
                            if(err) return callback(err);
                            gridStore.close(function (err, imgdata) {
                                if(err) logger.error(err.message);
                                callback(err, imgdata);
                            })
                        })
                    })
                })
        }
    })
}